<template>
    <view>
        <view class="payment-money text-price">{{ realityPayPrice }}</view>
        <view class="payment-time">剩余支付时间 {{ show_time }}</view>
        <view class="payment-select-payway-title">选择支付方式</view>
        <view>
            <view class="payment-select-payway-item" @tap.stop.prevent="oddcheckbox" data-index="1">
                <view class="flexs align-center">
                    <image :src="mallimgUrl + 'wechat.png'" class="payment-select-payway-icon"></image>
                    <view class="payment-select-payway-text">微信支付</view>
                </view>
                <checkbox-group>
                    <checkbox class="red" :checked="type == 1"></checkbox>
                </checkbox-group>
            </view>
            <view class="payment-select-payway-item" @tap.stop.prevent="oddcheckbox" data-index="2">
                <view class="flexs align-center">
                    <image :src="mallimgUrl + 'selfpay.png'" class="payment-select-payway-icon"></image>
                    <view class="payment-select-payway-text">余额支付（¥{{ balance }}）</view>
                </view>
                <checkbox-group>
                    <checkbox class="red" :checked="type == 2"></checkbox>
                </checkbox-group>
            </view>
        </view>
        <view class="payment-comfirm-btn" @tap="handlepay">确定</view>
        <!-- <van-overlay show="{{ show }}">
  <view class="overlay_main">
    <view class="overlay_top">
		<view class="title">
			<view class="icon" bindtap="hide"><van-icon name="cross" /></view>
			<view class="h1">请输入支付金额</view>
		</view>
		<view class="money">
			<view class="subtitle">支付金额</view>
			<view class="moneyMax">¥{{realityPayPrice}}</view>
		</view>
		<view class="balance">
			<text>余额</text>
			<text class="balanceMax">￥{{balance}}</text>
		</view>
		<view class="keyboardNum" bindtap="handleFocus">
			<text wx:for="{{valArr}}">{{item?'*':''}}</text>
			
		</view>
		<input value="{{valueData}}" focus="{{isFocus}}" maxlength="6" type="number" class='hidden-input text-white' bindinput="handleSetData" bindfocus="handleUseFocus" bindblur="handleUseFocus" />
    </view>
  </view> -->
        <van-overlay :show="show" @tap.native="hide">
            <view class="overlaybox" @tap.stop.prevent="shop">
                <view class="pab"><van-icon @click="hide" size="20px" name="cross" /></view>
                <view class="tit">请输入密码</view>
                <view class="tit1">支付金额</view>
                <view class="tit2">¥{{ realityPayPrice }}</view>
                <view class="hrs"></view>
                <view class="flexbox-sb centers p-20">
                    <text>余额</text>
                    <text class="t-c">￥{{ balance }}</text>
                </view>
                <padinput id="padinput" @infotan="getpassword($event, { tagId: 'padinput' })" :bool="true" :isFocus="isFocus"></padinput>
            </view>
        </van-overlay>
    </view>
</template>

<script>
const app = getApp();

const _request = require('../../utils/request.js');

const moment = require('../../utils/moment.min');

import md5 from '../../utils/md5.js';
var timerse;
let isPaying = false;
export default {
    data() {
        return {
            mallimgUrl: app.globalData.mallimgUrl,
            orderId: '',

            //订单id
            orderSn: '',

            //订单编号
            realityPayPrice: '',

            //支付金额
            createordertime: '',

            //创建订单时间
            show_time: '',

            //倒计时
            type: 1,

            //1微信支付 2余额支付
            balance: 0,

            //用户余额
            types: '',

            //类型 1-普通商城 2-意豆商城
            isLarge: '',

            isFocus: false,
            show: false,
            valArr: ['', '', '', '', '', ''],
            valueData: '',

            // 控制是否触发Unload函数
            isUnload: true,

            focusType: false,
            showpay: false
        };
    }, //
    onLoad: function (options) {
        console.log(options, 'options');
        this.setData({
            // orderId: options.orderId,
            orderSn: options.orderSn,
            realityPayPrice: options.realityPayPrice,
            createordertime: new moment(options.createordertime).valueOf(),
            types: options.type,
            isLarge: options.isLarge
        });
        this.gettimerse(); //倒计时

        this.getCashInfo(); //获取用户余额
    },
    onUnload: function () {
        clearInterval(timerse); // 防止支付成功触发两次

        if (this.isUnload) {
            uni.redirectTo({
                url: '/pages/mallorder/orderlist?_item=' + '_item'
            });
        }
    },
    methods: {
        hide() {
            this.setData({
                show: false
            });
        },

        // 获得焦点时
        handleUseFocus() {
            this.setData({
                focusType: true
            });
        },

        // 失去焦点时
        handleUseBlur() {
            this.setData({
                focusType: false
            });
        },

        // 点击6个框聚焦
        handleFocus() {
            this.setData({
                isFocus: true
            });
        },

        // 获取密码
        getpassword(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            this.setData({
                valueData: e.detail.inputValue
            });

            if (this.valueData.length == 6) {
                // _request.get('/settings/initPayWord', {
                //   userId: wx.getStorageSync('userid'),
                // }).then((res) => {
                //   if (res.data.message == '支付密码还未设置' && res.data.data == 0) {
                //     wx.showToast({
                //       title: '支付密码还未设置',
                //       icon: 'none',
                //       duration: 1000
                //     })
                //     setTimeout(() => {
                //       this.setData({
                //         showpay: false
                //       })
                //       wx.navigateTo({
                //         url: '/pages/setpaypassword/index',
                //       })
                //     }, 1000);
                //   } else if (res.data.message == '支付密码已设置' && res.data.data == 1) {
                _request
                    .postObj(
                        '/mall-order/balancePay',
                        {
                            orderSn: this.orderSn,
                            payWord: md5.hex(this.valueData + 'yiyue'),
                            // userId: wx.getStorageSync('userId'),
                            isLarge: this.isLarge,
                            type: this.types
                        },
                        app.globalData.mallType
                    )
                    .then((res) => {
                        if (res.data.code === 200) {
                            uni.showToast({
                                title: '支付成功',
                                icon: 'none'
                            });
                            this.setData(
                                {
                                    isUnload: false
                                },
                                () => {
                                    uni.redirectTo({
                                        url: '/pages/mallorder/orderlist?orderid=' + this.orderId + '&_item=' + '_item'
                                    });
                                }
                            );
                        } else if (res.data.code === 1001) {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                            setTimeout(() => {
                                this.setData({
                                    showpay: false
                                });
                                uni.navigateTo({
                                    url: '/pages/setpaypassword/index'
                                });
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    })
                    .catch((err) => {
                        uni.showToast({
                            title: err.data.message,
                            icon: 'none'
                        });
                    }); //   }
                // })
            }
        },

        // 获取输入框的值
        handleSetData(e) {
            // 更新数据
            console.log(e);
            let val = e.detail.value;
            let valArr = ['', '', '', '', '', ''];

            if (!isNaN(val)) {
            } else {
                val = val.slice(0, val.length - 1);
            }

            for (let i in val) {
                valArr[i] = val[i];
            }

            console.log(valArr);
            this.setData({
                valueData: val,
                valArr: valArr
            }); // 当输入框的值等于6时（发起支付等...）

            if (e.detail.value.length === 6) {
                _request
                    .postObj(
                        '/mall-order/balancePay',
                        {
                            orderSn: this.orderSn,
                            payWord: md5.hex(this.valueData + 'yiyue'),
                            // userId: wx.getStorageSync('userId'),
                            isLarge: this.isLarge,
                            type: this.types
                        },
                        app.globalData.mallType
                    )
                    .then((res) => {
                        if (res.data.code === 200) {
                            this.setData(
                                {
                                    isUnload: false
                                },
                                () => {
                                    uni.redirectTo({
                                        url: '/pages/mallorder/orderlist?orderid=' + this.orderId + '&_item=' + '_item'
                                    });
                                }
                            );
                        } else if (res.data.code === 1001) {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                            setTimeout(() => {
                                this.setData({
                                    showpay: false
                                });
                                uni.navigateTo({
                                    url: '/pages/setpaypassword/index'
                                });
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    })
                    .catch((err) => {
                        uni.showToast({
                            title: err.data.message,
                            icon: 'none'
                        });
                    }); // 通知用户输入数字达到6位数可以发送接口校验密码是否正确
                //
                // _request.postObj('/mallPay/checkPayWord', {
                //   userId: wx.getStorageSync('userId'),
                //   payWord:this.data.valueData
                // }, app.globalData.mallType).then(res=>{
                // 	if(res.data.code!==200){
                //     wx.showToast({
                //       title: res.data.message,
                //       icon:'none'
                //     })
                // 		//密码错误
                // 		this.setData({
                // 			valArr:['','','','','',''],
                // 			valueData: '',
                // 		})
                // 	  return  Promise.reject(res.data);
                // 	}else{
                // 		//密码正确
                // 	 	return  _request.postObj('/order/balancePay', {
                // 				orderSn:this.data.orderSn,
                // 			}, app.globalData.mallType)
                // 	}
                //   }).then((res) => {
                //     if (res.data.code === 200) {
                //       wx.redirectTo({
                //       url: '/pages/mallorder/orderinfo?orderid='+this.data.orderId,
                //       })
                //     }else{
                //       wx.showToast({
                //         title: res.data.message,
                //         icon:'none'
                //       })
                //     }
                //   }).catch(err=>{
                //     wx.showToast({
                //       title: err.data.message,
                //       icon:'none'
                //       })
                //     })
                //         // 判断是否有支付密码
                //   // 判断输入的密码是否正确
            }
        },

        gettimerse() {
            timerse = setInterval(() => {
                let createordertime = this.createordertime / 1000 + 86400; //结束待支付时间

                createordertime--;
                let now = new Date().getTime() / 1000; //当前时间换时间戳

                let diff = parseInt(createordertime - now);
                console.log(diff);

                if (diff < 0) {
                    clearInterval(timerse);
                    uni.navigateBack({
                        delta: 1
                    });
                } else {
                    let date = this.formattime(diff * 1000);
                    this.setData({
                        show_time: date
                    });
                }
            }, 1000);
        },

        //格式化时间
        formattime(time) {
            //格式化时间戳
            var leave1 = time % (24 * 3600 * 1000); //计算小时

            var hour = Math.floor(leave1 / (3600 * 1000));
            var leave2 = leave1 % (3600 * 1000); //计算分钟

            var minute = Math.floor(leave2 / (60 * 1000));
            var leave3 = leave2 % (60 * 1000); //计算秒

            var second = Math.round(leave3 / 1000) == '60' ? '00' : Math.round(leave3 / 1000);
            return [hour, minute, second].map(this.formatNumber).join(':');
        },

        formatNumber(n) {
            n = n.toString();
            return n[1] ? n : '0' + n;
        },

        // 获取用户余额
        getCashInfo(e) {
            _request
                .get(
                    '/user-asset/getUserWallet',
                    {
                        // userId: wx.getStorageSync('userId'),
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        this.setData({
                            balance: res.data.data.balance
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none'
                        });
                    }
                });
        },

        // 选择支付类型
        oddcheckbox(e) {
            this.setData({
                type: e.currentTarget.dataset.index
            });
        },

        // 调起支付
        handlepay: function () {
            if (this.type == 1) {
                // 微信支付, 防止重复支付
                if (isPaying) {
                    return;
                }

                isPaying = true;
                var that = this;
                uni.login({
                    success: (res) => {
                        var _code = res.code; // 1用户2理发师3门店

                        _request
                            .postObj(
                                '/mall-order/prepay',
                                {
                                    orderSn: that.orderSn,
                                    client: app.globalData.paytype,
                                    type: this.types,
                                    code: _code,
                                    isLarge: this.isLarge
                                },
                                app.globalData.mallType
                            )
                            .then((res) => {
                                console.log(res);

                                if (res.data.code === 200) {
                                    that.getrequestPayment(res.data.data); //微信支付
                                } else {
                                    isPaying = false;
                                    uni.showToast({
                                        title: res.data.message,
                                        icon: 'none'
                                    });
                                }
                            });
                    }
                });
            } else {
                // 余额支付
                // if(this.data.balance<=0 || !this.data.balance || this.data.realityPayPrice>=this.data.balance-0.01){
                //   wx.showToast({
                //     title: '余额不足',
                //     icon:'none'
                //   })
                //   return;
                // }
                this.setData({
                    show: true,
                    isFocus: true
                }); // _request.get('/mallPay/initPayWord', {
                //   userId: wx.getStorageSync('userId'),
                // }, app.globalData.mallType).then(res => {
                //   console.log(res)
                //   if (res.data.data === 1) {
                //     //设置了密码
                //     this.setData({
                //       show: true
                //     })
                //   } else {
                //     wx.showModal({
                //       title: '您还未设置密码',
                //       content: '请先设置密码',
                //       confirmText: '前往设置',
                //       success(res) {
                //         if (res.confirm) {
                //           wx.navigateTo({
                //             url: '/pages/setpaypassword/index',
                //           })
                //         } else if (res.cancel) {}
                //       }
                //     })
                //     // return  Promise.reject();
                //   }
                // }).catch(err => {
                //   wx.showToast({
                //     title: err.message,
                //     icon: 'none'
                //   })
                // })
            }
        },

        // 调起支付
        getrequestPayment(e) {
            var that = this;
            uni.requestPayment({
                timeStamp: e.timestamp,
                nonceStr: e.nonceStr,
                package: e.pkg,
                signType: e.signType,
                paySign: e.sign,
                success: function (r) {
                    that.setData(
                        {
                            isUnload: false
                        },
                        () => {
                            uni.redirectTo({
                                url: '/pages/mallorder/orderlist?orderid=' + that.orderId + '&_item=' + '_item'
                            });
                        }
                    );
                },
                fail: function (r) {
                    uni.showToast({
                        title: '支付失败!',
                        icon: 'none'
                    });
                    console.log('失败', r);
                },
                complete: function (r) {
                    isPaying = false;
                    console.log('完成', r);
                }
            });
        },

        shop() {
            console.log('占位：函数 shop 未声明');
        }
    }
};
</script>
<style>
.payment-wrap {
    background-color: #fbfbfb;
}
.payment-money {
    color: #ff1b0b;
    font-size: 66rpx;
    margin: 60rpx auto 20rpx auto;
    text-align: center;
    font-weight: bold;
}
.payment-time {
    font-size: 28rpx;
    margin: 30rpx auto;
    text-align: center;
}
.payment-select-payway-title {
    font-size: 50rpx;
    margin: 80rpx auto 60rpx auto;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
}
.payment-select-payway-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 0 40rpx 40rpx 40rpx;
    box-sizing: border-box;
}
.payment-select-payway-icon {
    width: 50rpx;
    height: 50rpx;
    margin-right: 20rpx;
}
.payment-select-payway-text {
    font-size: 28rpx;
}
.payment-comfirm-btn {
    font-size: 32rpx;
    width: 670rpx;
    color: #ffffff;
    background-color: #ff8722;
    margin: 100rpx auto 0 auto;
    line-height: 90rpx;
    text-align: center;
    border-radius: 80rpx;
}
.overlaybox {
    position: absolute;
    bottom: 0rpx;
    background: #ffffff;
    padding: 40rpx 20rpx;
    width: 650rpx;
    top: 20%;
    height: 460rpx;
    margin: 0 auto;
    left: 0;
    box-sizing: border-box;
    right: 0;
    border-radius: 10rpx;
}

.tit {
    width: 100%;
    text-align: center;
    margin-bottom: 40rpx;
}

.tit1 {
    width: 100%;
    text-align: center;
    font-size: 20rpx;
}

.tit2 {
    width: 100%;
    text-align: center;
    font-size: 40rpx;
    margin-bottom: 40rpx;
}

.p-20 {
    padding: 0 20rpx;
    margin-bottom: 30rpx;
}

.pab {
    position: absolute;
}

.t-c {
    color: #ff8722;
}
.balance {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    font-size: 24rpx;
    color: #666;
}
.balance .balanceMax {
    color: #ff8722;
}
.keyboardNum {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 0 30rpx;
    margin-top: 20rpx;
}
.keyboardNum text {
    width: 80rpx;
    height: 80rpx;
    background-color: #eee;
    text-align: center;
    line-height: 80rpx;
}
.hidden-input {
    opacity: 0;
    position: fixed;
    top: -10000rpx;
}
</style>
